package com.hqd.ch03.v34.web.servlet.mvc.method.annotation;

import com.hqd.ch03.v34.core.MethodParameter;
import com.hqd.ch03.v34.factory.ConfigurableBeanFactory;
import com.hqd.ch03.v34.spel.express.BeanExpressionContext;
import com.hqd.ch03.v34.web.bind.annotation.ValueConstants;
import com.hqd.ch03.v34.web.context.request.NativeWebRequest;
import com.hqd.ch03.v34.web.method.support.HandlerMethodArgumentResolver;

import javax.servlet.ServletException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver {


    private final ConfigurableBeanFactory configurableBeanFactory;
    private final Map<MethodParameter, NamedValueInfo> namedValueInfoCache = new ConcurrentHashMap<>(256);
    private BeanExpressionContext expressionContext;


    public AbstractNamedValueMethodArgumentResolver() {
        this.configurableBeanFactory = null;
        //   this.expressionContext = null;
    }

    public AbstractNamedValueMethodArgumentResolver(ConfigurableBeanFactory beanFactory) {
        this.configurableBeanFactory = beanFactory;
        /**
         * TODO：作用域
         */
//        this.expressionContext =
//                (beanFactory != null ? new BeanExpressionContext(beanFactory, new RequestScope()) : null);
    }


    @Override
    public final Object resolveArgument(MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
        /**
         * 获取目标参数名
         */
        NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
        MethodParameter nestedParameter = parameter.nestedIfOptional();

        Object resolvedName = namedValueInfo.name;
        if (resolvedName == null) {
            throw new IllegalArgumentException(
                    "Specified name must not resolve to null: [" + namedValueInfo.name + "]");
        }

        /**
         * 从request获取值，由子类实现
         */
        Object arg = resolveName(resolvedName.toString(), nestedParameter, webRequest);
        if (arg == null) {
            if (namedValueInfo.defaultValue != null) {
                arg = namedValueInfo.defaultValue;
            } else if (namedValueInfo.required && !nestedParameter.isOptional()) {
                handleMissingValue(namedValueInfo.name, nestedParameter, webRequest);
            }
            arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
        } else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
            arg = namedValueInfo.defaultValue;
        }

        handleResolvedValue(arg, namedValueInfo.name, parameter, webRequest);

        return arg;
    }

    /**
     * 获取对应的参数名
     */
    private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {
        NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);
        if (namedValueInfo == null) {
            namedValueInfo = createNamedValueInfo(parameter);
            namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);
            this.namedValueInfoCache.put(parameter, namedValueInfo);
        }
        return namedValueInfo;
    }


    protected abstract NamedValueInfo createNamedValueInfo(MethodParameter parameter);


    private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
        String name = info.name;
        if (info.name.isEmpty()) {
            name = parameter.getParameterName();
            if (name == null) {
                throw new IllegalArgumentException(
                        "Name for argument of type [" + parameter.getNestedParameterType().getName() +
                                "] not specified, and parameter name information not found in class file either.");
            }
        }
        String defaultValue = (ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
        return new NamedValueInfo(name, info.required, defaultValue);
    }


    protected abstract Object resolveName(String name, MethodParameter parameter, NativeWebRequest request)
            throws Exception;

    protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
            throws Exception {

        handleMissingValue(name, parameter);
    }

    protected void handleMissingValue(String name, MethodParameter parameter) throws ServletException {
        throw new RuntimeException("Missing argument '" + name +
                "' for method parameter of type " + parameter.getNestedParameterType().getSimpleName());
    }

    protected void handleMissingValueAfterConversion(String name, MethodParameter parameter, NativeWebRequest request)
            throws Exception {

        handleMissingValue(name, parameter, request);
    }

    private Object handleNullValue(String name, Object value, Class<?> paramType) {
        if (value == null) {
            if (Boolean.TYPE.equals(paramType)) {
                return Boolean.FALSE;
            } else if (paramType.isPrimitive()) {
                throw new IllegalStateException("Optional " + paramType.getSimpleName() + " parameter '" + name +
                        "' is present but cannot be translated into a null value due to being declared as a " +
                        "primitive type. Consider declaring it as object wrapper for the corresponding primitive type.");
            }
        }
        return value;
    }

    protected void handleResolvedValue(Object arg, String name, MethodParameter parameter,
                                       NativeWebRequest webRequest) {
    }

    protected static class NamedValueInfo {

        private final String name;

        private final boolean required;


        private final String defaultValue;

        public NamedValueInfo(String name, boolean required, String defaultValue) {
            this.name = name;
            this.required = required;
            this.defaultValue = defaultValue;
        }
    }

}
